<?php namespace lfy;

	abstract class pdo{
	
		protected static $dsn;
		
		protected static $username;
		
		protected static $password;
		
		protected static $driver_options;
		
		protected static $auto_error = E_USER_ERROR;
		
		protected static $attributes = array(
		
			/* 
				http://www.php.net/manual/en/pdo.setattribute.php 
				examples:
			*/
			
			# \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
			# \PDO::ATTR_ERRMODE => \PDO::ERRMODE_WARNING,
			# \PDO::ATTR_CASE => \PDO::CASE_LOWER,
			# \PDO::ATTR_ORACLE_NULLS => PDO::NULL_NATURAL,
			# \PDO::ATTR_STATEMENT_CLASS => array('classname', array('constructor_arg1', 'constructor_arg2'))
		
		);
		
		protected static $dbh;
		

		public static function get_dbh(){
		
			if(is_null(static::$dbh)){
				
				try {
				
					static::$dbh = new \PDO(static::$dsn, static::$username, static::$password, static::$driver_options);
					
				} catch(\Exception $e) {

					static::handle_exception($e);
					
					return false;
				
				}

				foreach(static::$attributes as $attr => $value){
					
					static::$dbh->setAttribute($attr, $value);
					
				}
								
			}
			
			return static::$dbh;
		
		}
		
		
		public static function close(){
			
			static::$dbh = NULL;
		
		}

		
		public static function __callStatic($name, $arguments){
			
			$dbh = static::get_dbh();
			
			$ret = call_user_func_array(
				array($dbh, $name), $arguments
			);
			
			if(static::$auto_error)
				static::handle_error($dbh->errorInfo(), $name, static::$auto_error);
		
			return $ret;
		
		}
		
		
		public static function handle_exception(\Exception $e){
		
			trigger_error($e->getMessage(), E_USER_ERROR);
		
		}
		
		
		public static function handle_error($e, $name, $level=E_USER_ERROR){
		
			if($e[2]) back_error($e[2], $level, 1, get_called_class()."::$name()");
		
		}

	}
